var SdsLocGroup = {
    departCode : $("#departCode").val(),
    departDesc : $("#departDesc").val()==null||$("#departDesc").val()==""?"全院":$("#departDesc").val(),
    tableIndex: $("#departCode").val()==null||$("#departCode").val()==""?"科室":"主治医师" ,//表格第一列描述
    analysisDicChart: null
};
$(function () {
    //科室组
    $('#departGroup').combobox({
        data:$.parseJSON($("#departGroupMap").val()),
        valueField:'value',
        textField:'text'
        //onSelect:ManageIndex.departChange
    });
    //病种
    $('#qcEntity').combobox({
        data:$.parseJSON($("#entityMap").val()),
        valueField:'value',
        textField:'text'
        //onSelect:ManageIndex.departChange
    });
    $('#startDate').datebox('setValue',timeStamp2String(new Date().getTime()-(1000 * 60 * 60 * 24*180)));
    $('#endDate').datebox('setValue',SdsLocGroup.getSystemTime());

    SdsLocGroup.initBottomTable();//加载主页低部表格数据
    //主页最上面文字描述
    $("#homeHtmlDesc").panel({title:"单病种科室填报统计"});
    //表格上面文字描述
    var desc = $("#qcEntity").combobox("getText");
    $("#homeTableDesc").panel({title:desc +"绩效报表数据"});
    //绑定顶部和中部蓝色数字的点击事件
    $(".homeCaseDeatil").click(function(){
        var _this = $(this);
        var key = _this.attr("id");
        /*var desc = _this.parent().prev().html();//父级的上一个同级元素*/
        var im_content=document.getElementById(key).parentNode;;
        var descText = im_content.innerText;
        var desc = descText.split("：")[0];
        SdsLocGroup.homeKeyDetail(key,desc,1);
    });
    $(".homeCaseDeatil2").click(function(){
        var _this = $(this);
        var key = _this.attr("id");
        var desc = _this.parent().prev().html();//父级的上一个同级元素
        SdsLocGroup.homeKeyDetail(key,desc,2);
    });
});

SdsLocGroup.search = function(){
    SdsLocGroup.initBottomTable();
};

/**
 * 加载主页底部表格数据
 */
SdsLocGroup.initBottomTable = function(){
    SdsLocGroup.entityChange();
};

/**
 * 根据病种绘制动态表头
 */
SdsLocGroup.entityChange = function(){
    var entityId = $("#qcEntity").combobox("getValue");
    var entityDesc = $("#qcEntity").combobox("getText");
    $('#departmentTable').bootstrapTable("destroy");//先销毁原来的表格
    buildTable(entityId,entityDesc);
}

/**
 * 钻取主页蓝色数字详细信息
 */
SdsLocGroup.homeKeyDetail = function(key,desc,type,entityId, locId){
    //type=1是从顶部蓝色数字传入，type=2表示从下面表格传入，如果是钻取的科室，传area参数暂时定为主治医师Id
    var startDate = "";
    var endDate = "";
    if ($('#startDate').datebox('getValue') != ""){
        startDate = $('#startDate').datebox('getValue')+" 00:00:00";//开始日期
        endDate = $('#endDate').datebox('getValue')+" 23:59:59";//开始日期
    }
    var departGroup = $("#departGroup").combobox("getValue");
    var qcEntity = $("#qcEntity").combobox("getValue");

    if(type==2){
        var href = Sys.backendPath + "/analysis/sdsmsta2/to_case2?key="+key+"&searchType=3&desc="+encodeURIComponent(desc) +"&startDate=" + startDate +"&endDate=" + endDate +"&office=" +"&depart=" +"&qcEntity=" + qcEntity;
    }else{
        var href = Sys.backendPath + "/analysis/sdsmsta2/to_case?key="+key+"&searchType=3&desc="+encodeURIComponent(desc) +"&startDate=" + startDate +"&endDate=" + endDate +"&office=" +"&depart=" +"&qcEntity=" + qcEntity+"&entityId=" + entityId+"&locId=" + locId;
    }

    layer.open({
        type: 2,
        title: ['<i class = "fa fa-list-ol"></i>&nbsp;'+desc,'padding-left:10px'],
        area:["95%","95%"],
        scrollbar: false,//为了禁止父页面滚动条滚动
        skin:'classfyLBStyle layer-ext-hisui',
        content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
    });
    //Sys.addTabPage($.trim(desc), href,true);

}

/**
 * 导出主页的表格数据
 */
SdsLocGroup.exportTable = function() {
    $("#tableDiv table").tableExport(
        {
            type : 'xlsx',
            escape : 'false'
        },SdsLocGroup.getSystemTime()+'全部绩效报表数据'
    )
};
/**
 * 获取当天年月日
 */
SdsLocGroup.getSystemTime = function(){
    function p(s) {
        return s < 10 ? '0' + s: s;
    }
    var date = new Date(); // 获取中国标准时间
    var y = date.getFullYear(); // 年
    var m = date.getMonth()+1; // 月
    var d = date.getDate(); // 日
    var sysTime = y+'-'+p(m)+'-'+p(d);
    return sysTime;
};

//在Jquery里格式化Date日期时间数据
function timeStamp2String(time){
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}
/**
 * 计算比率
 */
function MathMethod(a,b){
    if(b==0){
        return "0%";
    }
    var num = a/b;
    num = (num.toFixed(4)) * 100;  // 输出结果为 2.45
    var numStr = num.toString()
    var index = numStr.indexOf('.');
    if(index > -1){
        numStr = numStr.substring(0, index+3);
    }
    return numStr+"%";
}

SdsLocGroup.sumFieldValue = function(value,field){
    var upSum = 0;
    var patSum=0;
    var count = 0;
    for(var i in value){
        count += value[i][field];
        upSum += value[i]["reported"];
        patSum += value[i]["tofill"];
    }
    if(count==0){//如果是0返回空
        return "0"
    }

    if(field == "upRate") {
        return ((upSum/patSum)*100).toFixed(2)+"%";
    }
    
    return count
};

function mergeCells(data,fieldName,colspan,target){
    //声明一个map计算相同属性值在data对象出现的次数和
    var sortMap = {};
    for(var i = 0 ; i < data.length ; i++){
        for(var prop in data[i]){
            if(prop == fieldName){
                var key = data[i][prop]     //fieldName的value
                if(sortMap.hasOwnProperty(key)){
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
                break;
            }
        }
    }
    /*for(var prop in sortMap){
        console.log(prop,sortMap[prop])
    }*/
    //合并单元格
    var index = 0;
    for(var prop in sortMap){
        var count = sortMap[prop] * 1;
        $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
        index += count;
    }

}

//设置合计列宽度
function merge_footer(){
    //获取table表中footer 并获取到这一行的所有列
    var footer_tbody = $('.fixed-table-footer table tbody');
    var footer_tr = footer_tbody.find('>tr');
    var footer_td = footer_tr.find('>td');
    var footer_td_1 = footer_td.eq(0);
    for(var i=0;i<footer_td.length;i++){
        footer_td.eq(i).hide();//隐藏单元格
        if(i >= 0 && i <= 1){
            footer_td.eq(i).attr('width', "180px").show();//显示单元格并设置列宽
        }else {
            footer_td.eq(i).attr('width', "120px").show();//显示单元格并设置列宽
        }
    }
}

function buildTable(entityId,entityDesc){
    var columns = [],
        initColumns = [],//公共固定列
        itemColumns = []; //动态因子列
    initColumns = [
        {title: '科室组', field: 'locDesc', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId == "") {
                    value = "全院"
                }
                return value;
            },
            footerFormatter:function(value){
                return "<b>合计</b>";
            }
        },
        {title: '病种', field: 'entityDesc', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if ((row.locId != "" && row.entityId == "")||(row.locId == "")) {
                    value = "合计"
                }
                return value;
            },
            footerFormatter:function(value){
                return "<b></b>";
            }
        },
        {title: '符合入组', field: 'tofill', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;tofill&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-符合入组&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"tofill");
            }
        },
        {title: '待填报', field: 'unfill', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;unfill&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-待填报&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"unfill");
            }
        },
        {title: '已提交', field: 'submited', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;submited&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-已提交&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"submited");
            }
        },
        {title: '已审核', field: 'checked', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;checked&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-已审核&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"checked");
            }
        },
        {title: '已退回', field: 'backed', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;backed&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-已退回&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"backed");
            }
        },
        {title: '已上报', field: 'reported', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;reported&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-已上报&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"reported");
            }
        },
        {title: '上报率', field: 'upRate', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                return (value*100).toFixed(2)+"%";
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"upRate");
            }
        },
        {title: '10日内上报', field: 'in10DaysReported', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;in10DaysReported&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-10日内上报&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                }else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"in10DaysReported");
            }
        },
        {title: '超10日未上报', field: 'than10DaysNoReport', align: 'left', valign: 'middle', sortable: true,
            formatter:function(value,row,index){
                if (row.locId != "") {
                    return "<a onclick='SdsLocGroup.homeKeyDetail(&apos;than10DaysNoReport&apos;,&apos;" + row.locDesc + "|" + row.entityDesc + "-超10日未上报&apos;,3,&apos;" + row.entityId + "&apos;,&apos;" + row.locId + "&apos;)'>" + value + "</a>";
                } else {
                    return value;
                }
            },
            footerFormatter:function(value){
                return SdsLocGroup.sumFieldValue(value,"than10DaysNoReport");
            }
        }
    ];

    var params = {};
    var ajax = new $ax(Sys.backendPath + "/analysis/sdslocgroup/selectSdsLocGroupTable", function (data) {
        var dataTable = data.tableData;
        columns.push(initColumns, itemColumns); //合并表格内容
        this.$table =
            $('#departmentTable').bootstrapTable({
                data:dataTable,
                striped: false,//是否显示行间隔色
                pagination: false,//是否显示分页
                showFooter: false,
                //paginationLoop: false,
                //pageSize : 5,//用于设置每页初始显示的条数
                //pageList :[4],
                //sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
                sortName: "locId",
                sortOrder: 'desc',// desc  asc
                maintainSelected: true,//设为true 为选中的状态
                cache: false,
                search: false, //搜索框
                columns: columns,
                resizable: true,
                onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                    // $(".th-inner").css("font-weight","700");//表头字体加粗
                    $("#departmentTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
                        $(this).attr("title",$(this).text());
                    });
                },
                onPostBody:function (tableData) {
                    //merge_footer();
                }
            });
    }, function (data) {
    });
    params.departGroup = $("#departGroup").combobox("getValue");
    params.qcEntity = $("#qcEntity").combobox("getValue");
    params.startDate = $("#startDate").datebox("getValue") + " 00:00:00";
    params.endDate = $("#endDate").datebox("getValue") + " 23:59:59";
    ajax.set(params);
    ajax.start();
}